<!-- 查看作业页面 -->
<template>
    <div class="view-task-page" v-loading="loading">
        <TaskQuestion type="task-view" :data="taskInfo"/>
        <ul class="task-list">
            <li class="task-item">
                <p class="task-label">作答标题：</p>
                <p class="task-content">{{ taskInfo?.title || ''}}</p>
            </li>
            <li class="task-item" v-if="taskInfo?.answerContext">
                <p class="task-label">作答内容：</p>
                <p class="task-content">{{ taskInfo?.answerContext || ''}}</p>
            </li>
            <li class="task-item" v-if="taskInfo?.answerMaterialInfoList?.length">
                <p class="task-label">附件：</p>
                <ul v-if="taskInfo?.answerMaterialInfoList?.length" class="task-file-list">
                    <li v-for="item in taskInfo.answerMaterialInfoList" :key="item.materialId" class="task-file-item">
                        <FileItem type="download" :data="item"></FileItem>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</template>

<script setup>
import TaskQuestion from '@/views/answer-task/part/task-question.vue';
import FileItem from '@/views/answer-task/part/file-item.vue';
import { ref, onBeforeMount, watchEffect, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { jumpHref } from '@/router/jumpHref.js';

const store = useStore();

const route = useRoute();

const router = useRouter();

// 作业表单数据
const taskInfo = ref({
    name: '', // 作业名称
    context: '', // 作业内容
    homeWorkMaterialInfoList: [], // 作业附件
    title: '', // 作答标题
    answerContext: '', // 作答内容
    answerMaterialInfoList: [], // 作答附件
});

const loading = ref(false);

// 慕课详情数据
const detailData = ref({});

// 面包屑
const crumbList = ref([
    {
        name: '',
        route: {
            name: route.name === 'strainTaskDetail' ? 'strainDetail': 'detail',
            params: {
                moocId: route.params.moocId
            },
            query: {
                tab: 'CourseAssignment'
            }
        }
    }, {
        name: '作业作答'
    }
]);

// 获取作业详情
function getHomeworkInfo () {
    if (!route.query.taskId) {
        return false;
    }
    loading.value = true;
    G_transmit('homeworkInfo', {
        queries: {
            homeWorkId: route.query.taskId
        }
    }).then((res) => {
        taskInfo.value = res?.data || {};
        taskInfo.value.title = res?.data?.homeWorkAnswerVO?.title || '';
        taskInfo.value.answerContext = res?.data?.homeWorkAnswerVO?.context || '';
        taskInfo.value.answerMaterialInfoList = res?.data?.homeWorkAnswerVO?.answerMaterialInfoList || [];
    }).finally(() => {
        loading.value = false;
    })
}

const errorMsgMap = {
    'delete': '很抱歉，该慕课已下线', // 删除
    'disabled': '很抱歉，该慕课已下线', // 禁用
    'unpublished': '很抱歉，当前慕课还未发布，敬请期待', // 未发布
    'notsignup': '还未报名慕课哦，请先报名', // 没报名
    'noauthority': '很抱歉，您暂无查看权限' // 没权限
}

// 获取慕课详情
async function getDetail () {
    try {
        let res = await  G_transmit('moocDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })

        let result = res.data || {};

        detailData.value = result;
        crumbList.value[0].name = result.title || '';
        
        let isCourseUser = result?.isBuy; // 购买者

        let isPublish = result?.publishState == 1 && result?.state == 4;
        // 课程未发布 只有报过名的能看
        if (!isPublish && !isCourseUser) {
            G_dispatchEvent('toErrorPage', { title: errorMsgMap.unpublished, code: 500, target: jumpHref.home.mooc(), buttonLabel: '查看其他慕课'});
        }
        // 慕课发布未报名
        if (!isCourseUser) {
            let href = router.resolve({
              ...crumbList.value[0].route
            }).href;
            G_dispatchEvent('toErrorPage', { title: errorMsgMap.notsignup, code: 500, target: href, buttonLabel: '去报名'});
        }
        setBreadCrumb();
        getHomeworkInfo();
    } catch(_err) {
        // 禁用课程 30800500 删除课程 30800404
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            G_dispatchEvent('toErrorPage', { title: errorMsgMap.delete, code: 500, target: jumpHref.home.mooc(), buttonLabel: '查看其他慕课'});
        }  else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}

onBeforeMount(async() => {
    await store.dispatch('checkIsLogout');
    getDetail();
})

// 全部备案信息
const brand = computed(() => {
    return store.state.brand && store.state.brand.publishBrand ? store.state.brand.publishBrand : {};
})

// 具体备案信息
const brandInfo = computed(() => {
    return brand.value.brandConfig ? brand.value.brandConfig : {};
})

watchEffect(() => {
    let lessonName = detailData.value?.title ? detailData.value?.title : '';
    let siteName = brandInfo.value?.siteName ? '-' + brandInfo.value?.siteName : ''
    document.title = lessonName + siteName
})

// 面包屑
function setBreadCrumb() {
    store.dispatch('setBreadCrumb', [
        {
            ...crumbList.value[0]
        },
        {
            name: '查看作业'
        }
    ]);
}
</script>

<style lang="scss" scoped>
.view-task-page {
    width: 1200px;
    margin: 0 auto;
    background-color: #ffffff;
    border-radius: 4px;
    padding: 30px;
    min-height: 580px;
    font-family: MicrosoftYaHei;
    font-size: 14px;
    .task-list {
        .task-item {
            margin-bottom: 16px;
            display: flex;
            .task-label {
                width: 70px;
                color: var(--srt-color-gray);
                line-height: 19px;
                text-align: right;
            }
            .task-content {
                flex: 1;
                word-break: break-all;
            }
            .task-content1 {
                color: var(--srt-main-text-color);
            }
            .task-content2 {
                color: var(--srt-main-text-color);
                line-height: 21px;
            }
        }
    }
    .task-file-list {
        // margin-top: 20px;
        display: flex;
        flex-wrap: wrap;
        margin-bottom: -20px;
        .task-file-item {
            width: 480px;
            margin-right: 20px;
            margin-bottom: 20px;
        }
    }
}
</style>